package com.hmdp.service.impl;

import cn.hutool.json.JSONUtil;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisConstants;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;


@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public List<ShopType> getTypeList() {
        String redisShopTypeKey = RedisConstants.CACHE_SHOP_TYPELIST + "types";
        // 从Redis中查询
        List<String> shopTypes = stringRedisTemplate.opsForList().range(redisShopTypeKey, 0, -1);
        // 判断是否存在
        if (shopTypes != null && !shopTypes.isEmpty()){
            // 存在，直接返回
            List<ShopType> shopTypeList = shopTypes.stream().map(shopType ->
                    JSONUtil.toBean(shopType, ShopType.class))
                    .collect(ArrayList::new, ArrayList::add, ArrayList::addAll);
            // 重置过期时间
            stringRedisTemplate.expire(redisShopTypeKey, RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
            return shopTypeList;
        }

        // 不存在，查询数据库
        List<ShopType> typeList = query().orderByAsc("sort").list();
        // 不存在，返回报错
        if (typeList == null){
            return null;
        }
        // 存在，取出来保存Redis中
        for (ShopType type : typeList) {
            stringRedisTemplate.opsForList().rightPush(redisShopTypeKey, JSONUtil.toJsonStr(type));
        }
        stringRedisTemplate.expire(redisShopTypeKey, RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
        return typeList;
    }

}
